

import 'dart:ui';

import 'package:bike_ride/common/util/event_bus_utils.dart';
import 'package:bike_ride/common/util/sp_utils.dart';
import 'package:bike_ride/common/widget/picker_tool.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/res/global/globals.dart';
import 'package:flutter/cupertino.dart';

class Language {
  Language._();

  static final Language _instance = Language._();

  factory Language() => _instance;
  String get defaultLanguageCode => 'en';

  /// ISO 639 语言代码标准
  static final Map<String, String> languageMap = {
    'zh': '中文',
    'en': 'English',
    'id': 'Bahasa Indonesia',
    'ms': 'Bahasa Melayu',
    'th': 'ภาษาไทย',
  };
  /// 支持语言详情请查看[Globals.languageMap]
  bool get emptyLocale => SpUtils.getString(SpUtilsKey.$languageCode) =='';

  String? _locale; // 语言标识符，如'en'、'zh'等
  String get locale{
    if(_locale == null){
      if(emptyLocale){
        final List<Locale> systemLocales = window.locales;
        if (systemLocales.isNotEmpty && languageMap.keys.contains(systemLocales.first.languageCode)) {
          // 返回第一个语言的代码（通常是系统首选语言）
          setLocale(systemLocales.first.languageCode);
        }
      }else{
        setLocale(SpUtils.getString(SpUtilsKey.$languageCode));
      }
    }

    _locale ??= defaultLanguageCode;
    return _locale!;
  }
  static String get languageCode => SpUtils.getString(SpUtilsKey.$languageCode,defValue: 'en');
  static bool get isZh => languageCode == 'zh';

  void setLocale(String languageCode) {
    _locale = languageCode;
    SpUtils.putString(SpUtilsKey.$languageCode, _locale);
    EventBusUtils.fire(Locale);
  }

  initLocal(BuildContext context){
    if(emptyLocale){
      //自动弹出一次
      SpUtils.putString(SpUtilsKey.$languageCode, _locale);
      showPicker(context);
    }
  }

  /// 弹窗显示系统语言列表
  showPicker(BuildContext context){
    PickerTool.showStringPicker(
      context,
      languageMap.values.toList(),
      selecteds: [languageMap.keys.toList().indexOf(locale)],
      handleConfirm: (value) {
        setLocale(languageMap.keys.toList()[value[0]!]);
      },
      title: S.current.switchLanguage,
    );
  }

}